<?php
class Helper_BSS_XML
{
	static function ebayXMLToOrderArray($shop_id, $xml)
	{
		$orders = array();
		foreach ($xml->OrderArray[0] as $o)
		{
			if (isset($o->PaidTime[0]) && (string)$o->PaidTime[0] && (string)$o->CheckoutStatus[0]->eBayPaymentStatus[0] == 'NoPaymentFailure')
			{
				$country = Country::find('code=?', (string)$o->ShippingAddress[0]->Country[0])->asArray()->getOne();
				$country_name_en = $country ? $country['en_name'] : (string)$o->ShippingAddress[0]->Country[0];
				$country_name_cn = $country ? $country['cn_name'] : '';
				$currency = $o->AmountPaid[0]->attributes();
				$currency_db = Currency::find('code=?', (string)$currency['currencyID'])->asArray()->getOne();
				$new = array();
				$phone = (string)$o->ShippingAddress[0]->Phone[0];
				$email = (string) $o->TransactionArray[0]->Transaction[0]->Buyer[0]->Email[0];
				$new['shop_id'] = $shop_id;
				$new['shop_order_number'] = (string)$o->ShippingDetails[0]->SellingManagerSalesRecordNumber[0];
				$new['paid_time'] = isset($o->PaidTime[0]) ? date('Y-m-d H:i:s', strtotime($o->PaidTime[0])) : 0;
				$new['sales_time'] = date('Y-m-d H:i:s', strtotime($o->CreatedTime[0]));
				$new['shop_buyer_id'] = (string)$o->BuyerUserID[0];
				$new['fullname'] = (string)$o->ShippingAddress[0]->Name[0];
				$new['phone'] = ($phone == 'Invalid Request') ? '' : $phone;
				$new['email'] = ($email == 'Invalid Request') ? '' : $email;
				$new['street1'] = (string)$o->ShippingAddress[0]->Street1[0];
				$new['street2'] = (string)$o->ShippingAddress[0]->Street2[0];
				$new['city'] = (string)$o->ShippingAddress[0]->CityName[0];
				$new['state'] = (string)$o->ShippingAddress[0]->StateOrProvince[0];
				$new['state'] = $new['state'] ? $new['state'] : $new['city'];
				$new['zip'] = (string)$o->ShippingAddress[0]->PostalCode[0];
				$new['country'] = $country_name_en;
				$new['country_cn'] = $country_name_cn;
				$new['currency_id'] = $currency_db['id'];
				$new['currency_rate'] = $currency_db['rate'];
				$new['shipping_fee'] = (string)$o->ShippingServiceSelected[0]->ShippingServiceCost[0];
				$new['shipping_method'] = ($country_name_en == 'United States') ? Shipping_Method::getShippingMethodByCode('GZ_N_EUB') : Shipping_Method::getShippingMethodByCode('GZ_N_HK_Package');
				$new['discount'] = 0;
				$new['amount'] = (string)$o->AmountPaid[0];
				$new['payment_method'] = Q::ini('custom_flag/sales_order_payment_method/paypal/value');
				$new['transaction_id'] = isset($o->ExternalTransaction) ? (string)$o->ExternalTransaction[0]->ExternalTransactionID[0] : '';
				$new['buyer_message'] = isset($o->BuyerCheckoutMessage) ? (string)$o->BuyerCheckoutMessage[0] : '';
				$item = array();
				foreach ($o->TransactionArray[0] as $i)
				{
					$sku = isset($i->Variation[0]->SKU) ? (string)$i->Variation[0]->SKU[0] : (string)$i->Item[0]->SKU[0];
					$quantity = (string)$i->QuantityPurchased[0];
					$price = (string)$i->TransactionPrice[0];
					$finalvaluefee = (string)$i->FinalValueFee[0];
					$sku_and_quantity = explode('+', $sku);
					$product_bind = Product_Bind::find('number=?', $sku_and_quantity[0])->asArray()->getOne();
					if ($product_bind['id'])
					{
						$product_bind_item = Product_Bind_Item::find('product_bind_item.product_bind_id=?', $product_bind['id'])
							->joinLeft('product_basic', 'number', 'product_basic.id=product_bind_item.product_basic_id')
							->asArray()->getAll();
						foreach ($product_bind_item as $k => $pbi)
						{
							$new_item = array();
							if ($k != 0)
							{
								$price = 0;
								$new_item['shop_item_id'] = '';
								$new_item['shop_transaction_id'] = '';
								$new_item['gift_flag'] = Q::ini('custom_flag/sales_order_item_gift_flag/gift/value');
							}
							else
							{
								$price = sprintf('%.2f', $price / intval($pbi['quantity']));
								$new_item['shop_item_id'] = (string)$i->Item[0]->ItemID[0];
								$new_item['shop_transaction_id'] = (string)$i->TransactionID[0];
							}
							$new_item['product_basic_number'] = $pbi['number'];
							$new_item['quantity'] = $pbi['quantity'] * $quantity;
							$new_item['sales_price'] = $price;
							$new_item['fee'] = $finalvaluefee;
							$item[] = $new_item;
						}
					}
					else
					{
						foreach ($sku_and_quantity as $k => $saq)
						{
							$new_item = array();
							if ($k == 0)
							{
								$new_item['shop_item_id'] = (string)$i->Item[0]->ItemID[0];
								$new_item['shop_transaction_id'] = (string)$i->TransactionID[0];
							}
							else
							{
								$price = 0;
								$new_item['shop_item_id'] = '';
								$new_item['shop_transaction_id'] = '';
								$new_item['gift_flag'] = Q::ini('custom_flag/sales_order_item_gift_flag/gift/value');
							}
							$single_sku_and_quantity = explode('-', $saq);
							$new_item['product_basic_number'] = $single_sku_and_quantity[0];
							if (isset($single_sku_and_quantity[1]))
							{
								$new_item['quantity'] = $quantity * intval($single_sku_and_quantity[1]);
								$new_item['sales_price'] = $price / intval($single_sku_and_quantity[1]);
							}
							else
							{
								$new_item['quantity'] = $quantity;
								$new_item['sales_price'] = $price;
							}
							$new_item['fee'] = $finalvaluefee;
							$item[] = $new_item;
						}
					}
				}
				$new['item'] = $item;
				$orders[] = $new;
			}
		}
		return $orders;
	}

	static function ebayXMLToListingArray($shop_id, $xml)
	{
		set_time_limit(0);
		$listing = array();
		if ((int)$xml->ReturnedItemCountActual[0] > 0)
		{
			foreach ($xml->ItemArray[0] as $i)
			{
				if ( ! empty($i->Variations[0]))
				{
					foreach ($i->Variations[0] as $iv)
					{
						$new = array();
						$new['variation_flag'] = Q::ini('custom_flag/online_ebay_listing_variation_flag/variation/value');
						$new['shop_id'] = $shop_id;
						$new['shop_item_id'] = (string)$i->ItemID[0];
						$new['title'] = (string)$i->Title[0];
						$new['currency'] = (string)$i->Currency[0];
						$new['status'] = (string)$i->SellingStatus[0]->ListingStatus[0];
						$new['type'] = (string)$i->ListingType[0];
						$new['duration'] = (string)$i->ListingDuration[0];
						$new['start_time'] = date('Y-m-d H:i:s', strtotime((string)$i->ListingDetails[0]->StartTime[0]));
						$new['end_time'] = date('Y-m-d H:i:s', strtotime((string)$i->ListingDetails[0]->EndTime[0]));
						$new['item_url'] = (string)$i->ListingDetails[0]->ViewItemURL[0];
						$new['gallery_url'] = (string)$i->PictureDetails[0]->GalleryURL[0];
						$new['sku'] = (string)$iv->SKU[0];
						$new['quantity'] = (int)$iv->Quantity[0] - (int)$iv->SellingStatus[0]->QuantitySold[0];
						$new['sold_quantity'] = (int)$iv->SellingStatus[0]->QuantitySold[0];
						$new['start_price'] = (string)$iv->StartPrice[0];
						$new['site_id'] = (string)$i->Site[0];
						$new['watch_count'] = (string)$i->WatchCount[0];
						$listing[] = $new;
					}
				}
				else
				{
					$new = array();
					$new['variation_flag'] = Q::ini('custom_flag/online_ebay_listing_variation_flag/non-variation/value');
					$new['shop_id'] = $shop_id;
					$new['shop_item_id'] = (string)$i->ItemID[0];
					$new['title'] = (string)$i->Title[0];
					$new['currency'] = (string)$i->Currency[0];
					$new['status'] = (string)$i->SellingStatus[0]->ListingStatus[0];
					$new['type'] = (string)$i->ListingType[0];
					$new['duration'] = (string)$i->ListingDuration[0];
					$new['start_time'] = date('Y-m-d H:i:s', strtotime((string)$i->ListingDetails[0]->StartTime[0]));
					$new['end_time'] = date('Y-m-d H:i:s', strtotime((string)$i->ListingDetails[0]->EndTime[0]));
					$new['item_url'] = (string)$i->ListingDetails[0]->ViewItemURL[0];
					$new['gallery_url'] = (string)$i->PictureDetails[0]->GalleryURL[0];
					$new['sku'] = (string)$i->SKU[0];
					$new['quantity'] = (int)$i->Quantity[0] - (int)$i->SellingStatus[0]->QuantitySold[0];
					$new['sold_quantity'] = (int)$i->SellingStatus[0]->QuantitySold[0];
					$new['start_price'] = (string)$i->StartPrice[0];
					$new['site_id'] = (string)$i->Site[0];
					$new['watch_count'] = (string)$i->WatchCount[0];
					$listing[] = $new;
				}
			}
		}
		return $listing;
	}
	
	static function ebayXMLToMessageArray($shop_id, $xml)
	{
		$messages = array();
		foreach ($xml->Messages[0]->Message as $m)
		{
			$new = array();
			$new['sender'] = (string)$m->Sender[0];
			$new['recipient'] = (string)$m->RecipientUserID[0];
			$new['subject'] = (string)$m->Subject[0];
			$new['message_id'] = (string)$m->MessageID[0];
			$new['external_message_id'] = isset($m->ExternalMessageID[0]) ? (string)$m->ExternalMessageID[0] : '';
			$new['read'] = (string)$m->Read[0] == 'true' ? 1 : 0;
			$new['flagged'] = (string)$m->Flagged[0] == 'true' ? 1 : 0;
			$new['receive_time'] = date('Y-m-d H:i:s', strtotime((string)$m->ReceiveDate[0]));
			$new['expiration_time'] = date('Y-m-d H:i:s', strtotime((string)$m->ExpirationDate[0]));
			$new['shop_item_id'] = isset($m->ItemID[0]) ? (string)$m->ItemID[0] : '';
			$new['shop_id'] = $shop_id;
			$new['response_enabled'] = (string)$m->ResponseDetails[0]->ResponseEnabled[0] == 'true' ? 1 : 0;
			$new['response_url'] = isset($m->ResponseDetails[0]->ResponseURL[0]) ? (string)$m->ResponseDetails[0]->ResponseURL[0] : '';
			$new['response_time'] = isset($m->ResponseDetails[0]->UserResponseDate[0]) ? date('Y-m-d H:i:s', strtotime((string)$m->ResponseDetails[0]->UserResponseDate[0])) : '';
			$new['folder_id'] = (string)$m->Folder[0]->FolderID[0];
			$new['replied'] = (string)$m->Replied[0] == 'true' ? 1 : 0;
			$k = 0;
			foreach ($m->MessageMedia as $mm)
			{
				$new['pictures'][$k]['name'] = (string)$mm->MediaName;
				$new['pictures'][$k]['url'] = (string)$mm->MediaURL;
				$k++;
			}
			$messages[] = $new;
		}
		return $messages;
	}
	
	static function ebayXMLToCasesArray($shop_id, $xml)
	{
		$cases = array();
		foreach ($xml->cases[0]->caseSummary as $c)
		{
			$new = array();
			$new['case_id'] = (string)$c->caseId[0]->id[0];
			$new['shop_item_id'] = (string)$c->item[0]->itemId[0];
			$new['type'] = Q::ini('custom_flag/services_ebay_case_type/' . (string)$c->caseId[0]->type[0] . '/value');
			$status = Q::ini('custom_flag/services_ebay_case_type/' . (string)$c->caseId[0]->type[0] . '/status_name');
			$new['status'] = (string)$c->status[0]->$status;
			$new['shop_id'] = $shop_id;
			$new['buyer'] = isset($c->otherParty[0]->userId[0]) ? (string)$c->otherParty[0]->userId[0] : '';
			$new['amount'] = (float)$c->caseAmount[0];
			$new['quantity'] = (int)$c->caseQuantity[0];
			$new['create_time'] = date('Y-m-d H:i:s', strtotime((string)$c->creationDate[0]));
			$new['update_time'] = date('Y-m-d H:i:s', strtotime((string)$c->lastModifiedDate[0]));
			$cases[] = $new;
		}
		return $cases;
	}
	
	static function ebayXMLToCaseDetailArray($services_ebay_case_id, $xml)
	{
		$message = array();
		foreach ($xml->caseDetail[0]->responseHistory as $r)
		{
			$new = array();
			$new['services_ebay_case_id'] = $services_ebay_case_id;
			$new['author_role'] = (string)$r->author[0]->role[0];
			$new['message'] = isset($r->note[0]) ? (string)$r->note[0] : '';
			$new['description'] = (string)$r->activityDetail[0]->description[0];
			if ($new['description'] == 'Seller provided tracking information for shipment.')
			{
				$new['shipping_carrier'] = isset($xml->caseDetail[0]->sellerShipment[0]->carrierUsed[0]) ? (string)$xml->caseDetail[0]->sellerShipment[0]->carrierUsed[0] : '';
				$new['tracking_number'] =  isset($xml->caseDetail[0]->sellerShipment[0]->trackingNumber[0]) ? (string)$xml->caseDetail[0]->sellerShipment[0]->trackingNumber[0] : '';
			}
			if ($new['description'] == 'Seller provided shipping information.')
			{
				$new['shipping_carrier'] = isset($xml->caseDetail[0]->sellerShipment[0]->carrierUsed[0]) ? (string)$xml->caseDetail[0]->sellerShipment[0]->carrierUsed[0] : '';
				$new['shipped_time'] = isset($xml->caseDetail[0]->sellerShipment[0]->deliveryDate[0]) ? date('Y-m-d H:i:s', strtotime((string)$xml->caseDetail[0]->sellerShipment[0]->deliveryDate[0])) : '';
			}
			if ($new['description'] == 'PayPal account refunded by RCS callback.')
			{
				$new['refund'] = ((string)$xml->caseDetail[0]->agreedRefundAmount[0] == '0.0') ? (string)$xml->caseSummary[0]->caseAmount[0] : (string)$xml->caseDetail[0]->agreedRefundAmount[0];
				$new['refund_transaction_id'] = isset($xml->caseDetail[0]->paymentDetail[0]->moneyMovement[0]->paypalTransactionId[0]) ? (string)$xml->caseDetail[0]->paymentDetail[0]->moneyMovement[0]->paypalTransactionId[0] : '';
			}
			if ($new['description'] == 'Seller issued partial refund to buyer.')
			{
				$new['refund'] = (string)$xml->caseDetail[0]->agreedRefundAmount[0];
			}
			if ($new['description'] == 'Seller has requested return of the item/order.')
			{
				$new['message'] = "return address:\n";
				$new['message'] .= isset($xml->caseDetail[0]->buyerReturnShipment[0]->shippingAddress[0]->name[0]) ? ((string)$xml->caseDetail[0]->buyerReturnShipment[0]->shippingAddress[0]->name[0] . "\n") : '';
				$new['message'] .= (string)$xml->caseDetail[0]->buyerReturnShipment[0]->shippingAddress[0]->street1[0] . "\n";
				$new['message'] .= (string)$xml->caseDetail[0]->buyerReturnShipment[0]->shippingAddress[0]->city[0] . " ";
				$new['message'] .= (string)$xml->caseDetail[0]->buyerReturnShipment[0]->shippingAddress[0]->stateOrProvince[0] . " ";
				$new['message'] .= (string)$xml->caseDetail[0]->buyerReturnShipment[0]->shippingAddress[0]->postalCode[0] . "\n";
				$new['message'] .= isset($xml->caseDetail[0]->buyerReturnShipment[0]->shippingAddress[0]->country[0]) ? ((string)$xml->caseDetail[0]->buyerReturnShipment[0]->shippingAddress[0]->country[0] . "\n") : '';
			}
			$new['response_time'] = date('Y-m-d H:i:s', strtotime((string)$r->creationDate[0]));
			$message[] = $new;
		}
		return $message;
	}
	
	static function ebayXMLToFeedbackArray($shop_id, $xml)
	{
		$feedback = array();
		if ($xml->FeedbackDetailArray[0]->FeedbackDetail)
		{
			foreach ($xml->FeedbackDetailArray[0]->FeedbackDetail as $f)
			{
				$new = array();
				$new['feedback_id'] = (string)$f->FeedbackID[0];
				$new['shop_id'] = $shop_id;
				$new['shop_item_id'] = (string)$f->ItemID[0];
				$new['transaction_id'] = isset($f->TransactionID[0]) ? (string)$f->TransactionID[0] : 0;
				$new['user'] = (string)$f->CommentingUser[0];
				$new['left_role'] = Q::ini('custom_flag/services_ebay_feedback_left_role/' . (string)$f->Role[0] . '/value');
				$new['score'] = (string)$f->CommentingUserScore[0];
				$new['type'] = Q::ini('custom_flag/services_ebay_feedback_type/' . (string)$f->CommentType[0] . '/value');
				$new['content'] = trim((string)$f->CommentText[0]);
				$new['create_time'] = date('Y-m-d H:i:s', strtotime((string)$f->CommentTime[0]));
				$new['response'] = isset($f->FeedbackResponse[0]) ? (string)$f->FeedbackResponse[0] : '';
				if (isset($f->ItemPrice[0]))
				{
					$currency = (string)$f->ItemPrice[0]->attributes();
					$currency_db = Currency::find('code=?', $currency)->asArray()->getOne();
					$new['currency_id'] = $currency_db['id'];
					$new['item_price'] = (string)$f->ItemPrice[0];
				}
				else
				{
					$new['currency_id'] = '';
					$new['item_price'] = '';
				}
				$feedback[] = $new;
			}
		}
		$total_entries = 0;
		if ($xml->FeedbackSummary[0]->TotalFeedbackPeriodArray[0]->FeedbackPeriod)
		{
			foreach ($xml->FeedbackSummary[0]->TotalFeedbackPeriodArray[0]->FeedbackPeriod as $fp)
			{
				if ((string)$fp->PeriodInDays[0] == '30')
				{
					$total_entries = (string)$fp->Count[0];
					break;
				}
			}
		}
		return array('feedback' => $feedback, 'total_entries' => $total_entries);
	}
	
	static function ebayXMLToCategoriesArray($xml, $site)
	{
		$categories = array();
		if ($xml->CategoryArray[0]->Category[0])
		{
			foreach ($xml->CategoryArray[0]->Category as $c)
			{
				if ( ! (isset($c->Expired[0]) && (string)$c->Expired[0]))
				{
					$new = array();
					$new['id'] = (int)$c->CategoryID[0];
					$new['name'] = (string)$c->CategoryName[0];
					$new['parent_id'] = (int)$c->CategoryParentID[0];
					$new['site'] = $site;
					$new['level'] = (int)$c->CategoryLevel[0];
					$new['leaf'] = isset($c->LeafCategory[0]) && (string)$c->LeafCategory[0] ? 1 : 0;
					$categories[] = $new;
				}
			}
		}
		return $categories;
	}
	
	static function ebayXMLToStoreCategoriesArray($xml)
	{
		$categories = array();
		if (isset($xml->Store[0]->CustomCategories[0]->CustomCategory[0]))
		{
			foreach ($xml->Store[0]->CustomCategories[0]->CustomCategory as $c)
			{
				$c_name = (string)$c->Name[0];
				if (isset($c->ChildCategory[0]))
				{
					foreach ($c->ChildCategory as $cc)
					{
						$cc_name = (string)$cc->Name[0];
						if (isset($cc->ChildCategory[0]))
						{
							foreach ($cc->ChildCategory as $ccc)
							{
								$ccc_name = (string)$ccc->Name[0];
								$categories[(string)$ccc->CategoryID[0]] = $c_name . ' > ' . $cc_name . ' > ' . $ccc_name;
							}
						}
						else
						{
							$categories[(string)$cc->CategoryID[0]] = $c_name . ' > ' . $cc_name;
						}
					}
				}
				else
				{
					$categories[(string)$c->CategoryID[0]] = $c_name;
				}
			}
		}
		return $categories;
	}
	
	static function ebayXMLToCategoriesFeatureArray($xml)
	{
		$feature = array();
		/*
		 * 判断是否可以创建多SKU
		 */
		$variation = '';
		if (isset($xml->Category[0]->VariationsEnabled[0]))
		{
			$variation = 1;
		}
		$feature['variation'] = $variation;
		/*
		 * 获取产品条件信息
		 */
		$condition = array();
		if (isset($xml->Category[0]->ConditionValues[0]->Condition[0]))
		{
			foreach ($xml->Category[0]->ConditionValues[0]->Condition as $c)
			{
				$new = array();
				$new['value'] = (int)$c->ID;
				$new['name'] = (string)$c->DisplayName;
				$condition[] = $new;
			}
		}
		$feature['condition'] = $condition;
		return $feature;
	}
	
	static function ebayXMLToCategoriesSpecificArray($xml)
	{
		$specific = array();
		if (isset($xml->Recommendations[0]->NameRecommendation[0]))
		{
			foreach ($xml->Recommendations[0]->NameRecommendation as $s)
			{
				$new = array();
				$new['name'] = (string)$s->Name[0];
				$new['freetext'] = '';
				if ((string)$s->ValidationRules[0]->SelectionMode[0] == 'FreeText')
				{
					$new['freetext'] = 1;
				}
				$new['variation'] = 1;
				if (isset($s->ValidationRules[0]->VariationSpecifics[0]) && (string)$s->ValidationRules[0]->VariationSpecifics[0] == 'Disabled')
				{
					$new['variation'] = 0;
				}
				$new['require'] = 0;
				if (isset($s->ValidationRules[0]->MinValues[0]) && (int)$s->ValidationRules[0]->MinValues[0] >= 1)
				{
					$new['require'] = 1;
				}
				$new['option'] = array();
				foreach ($s->ValueRecommendation as $v)
				{
					$new['option'][] = htmlspecialchars((string)$v->Value[0]);
				}
				$specific[] = $new;
			}
		}
		return $specific;
	}
	
	static function ebayXMLToEbayDetailsArray($xml)
	{
		$details = array();
		/*
		 * 获取邮寄的信息
		 * $domestic_shipping 国内物流方式
		 * $internation_shipping 国际物流方式
		 */
		$domestic_shipping = $internation_shipping = array();
		if (isset($xml->ShippingServiceDetails[0]))
		{
			foreach ($xml->ShippingServiceDetails as $s)
			{
				if ((string)$s->ValidForSellingFlow[0])
				{
					$type = array();
					foreach ($s->ServiceType as $st)
					{
						$type[] = (string)$st;
					}
					$category = ucfirst(strtolower((string)$s->ShippingCategory[0]));
					$id = (int)$s->ShippingServiceID[0];
					$new = array(
						'id' => $id,
						'value' => (string)$s->ShippingService[0],
						'name' => (string)$s->Description[0],
						'max_time' => isset($s->ShippingTimeMax) ? (string)$s->ShippingTimeMax[0] : '',
						'min_time' => isset($s->ShippingTimeMin[0]) ? (string)$s->ShippingTimeMin[0] : '',
					);
					if (isset($s->InternationalService) && (string)$s->InternationalService)
					{
						foreach ($type as $t)
						{
							$internation_shipping[$t][$category][$id] = $new;
						}
					}
					else
					{
						foreach ($type as $t)
						{
							$domestic_shipping[$t][$category][$id] = $new;
						}
					}
				}
			}
			foreach ($domestic_shipping as &$ls)
			{
				ksort($ls);
			}
			unset($ls);
			foreach ($internation_shipping as &$is)
			{
				ksort($is);
			}
			unset($is);
		}
		$details['shipping_service']['domestic'] = $domestic_shipping;
		$details['shipping_service']['internation'] = $internation_shipping;
		/*
		 * 获取邮寄到达的国家
		 */
		$shipping_location = array();
		if (isset($xml->ShippingLocationDetails[0]))
		{
			foreach ($xml->ShippingLocationDetails as $d)
			{
				if ( ! in_array((string)$d->ShippingLocation[0], array('None', 'Worldwide')))
				{
					$new = array();
					$new['value'] = (string)$d->ShippingLocation[0];
					$new['name'] = (string)$d->Description[0];
					$shipping_location[] = $new;
				}
			}
		}
		$details['shipping_location'] = $shipping_location;
		/*
		 * 获取派遣时间的信息
		 */
		$dispatch_time = array();
		if (isset($xml->DispatchTimeMaxDetails[0]))
		{
			foreach ($xml->DispatchTimeMaxDetails as $d)
			{
				$new = array();
				$new['value'] = (string)$d->DispatchTimeMax[0];
				$new['name'] = (string)$d->Description[0];
				$dispatch_time[] = $new;
			}
			$dispatch_time = Helper_BSS_Array::SortByValue($dispatch_time, 'value', 'asc');
		}
		/*
		 * 获取退货政策的信息
		 */
		$return_policy = array();
		if (isset($xml->ReturnPolicyDetails[0]))
		{
			$return_policy['return_accepted'] = array();
			foreach ($xml->ReturnPolicyDetails[0]->ReturnsAccepted as $r)
			{
				$new = array();
				$new['value'] = (string)$r->ReturnsAcceptedOption[0];
				$new['name'] = (string)$r->Description[0];
				$return_policy['return_accepted'][] = $new;
			}
			$return_policy['refund'] = array();
			foreach ($xml->ReturnPolicyDetails[0]->Refund as $r)
			{
				$new = array();
				$new['value'] = (string)$r->RefundOption[0];
				$new['name'] = (string)$r->Description[0];
				$return_policy['refund'][] = $new;
			}
			$return_policy['return_within'] = array();
			foreach ($xml->ReturnPolicyDetails[0]->ReturnsWithin as $r)
			{
				$new = array();
				$new['value'] = (string)$r->ReturnsWithinOption[0];
				$new['name'] = (string)$r->Description[0];
				$return_policy['return_within'][] = $new;
			}
			$return_policy['paid_by'] = array();
			foreach ($xml->ReturnPolicyDetails[0]->ShippingCostPaidBy as $s)
			{
				$new = array();
				$new['value'] = (string)$s->ShippingCostPaidByOption[0];
				$new['name'] = (string)$s->Description[0];
				$return_policy['paid_by'][] = $new;
			}
			$return_policy['restock'] = array();
			foreach ($xml->ReturnPolicyDetails[0]->RestockingFeeValue as $r)
			{
				$new = array();
				$new['value'] = (string)$r->RestockingFeeValueOption[0];
				$new['name'] = (string)$r->Description[0];
				$return_policy['restock'][] = $new;
			}
		}
		$details['dispatch_time'] = $dispatch_time;
		$details['return_policy'] = $return_policy;
		return $details;
	}
	
	static function ebayXMLToListingsArray($shop_id, $xml)
	{
		set_time_limit(0);
		$listings = array();
		if ((int)$xml->ReturnedItemCountActual[0] > 0)
		{
			foreach ($xml->ItemArray[0] as $item)
			{
				$new = array();
				$new['shop_id'] = $shop_id;
				$new['site'] = (string)$item->Site[0];
				$new['currency'] = (String)$item->Currency[0];
				$new['shop_item_id'] = (string)$item->ItemID[0];
				$new['primary_categories'] = (string)$item->PrimaryCategory[0]->CategoryID[0];
				$new['primary_categories_name'] = (string)$item->PrimaryCategory[0]->CategoryName[0];
				$new['second_categories'] = isset($item->SecondaryCategory[0]->CategoryID[0]) ? (string)$item->SecondaryCategory[0]->CategoryID[0] : '';
				$new['second_categories_name'] = isset($item->SecondaryCategory[0]->CategoryName[0]) ? (string)$item->SecondaryCategory[0]->CategoryName[0] : '';
				$new['store_categories'] = isset($item->Storefront[0]->StoreCategoryID[0]) ? (string)$item->Storefront[0]->StoreCategoryID[0] : '';
				$new['store_categories_name'] = isset($item->Storefront[0]->StoreCategoryName[0]) ? (string)$item->Storefront[0]->StoreCategoryName[0] : '';
				$new['store_categories2'] = isset($item->Storefront[0]->StoreCategory2ID[0]) ? (string)$item->Storefront[0]->StoreCategory2ID[0] : '';
				$new['store_categories2_name'] = isset($item->Storefront[0]->StoreCategory2Name[0]) ? (string)$item->Storefront[0]->StoreCategory2Name[0] : '';
				$new['title'] = (string)$item->Title[0];
				$new['condition_id'] = isset($item->ConditionID[0]) ? (string)$item->ConditionID[0] : '';
				$new['condition_name'] = isset($item->ConditionDisplayName[0]) ? (string)$item->ConditionDisplayName[0] : '';
				$new['condition_description'] = isset($item->ConditionDescription[0]) ? (string)$item->ConditionDescription[0] : '';
				$new['listing_type'] = (string)$item->ListingType[0];
				$new['listing_duration'] = (string)$item->ListingDuration[0];
				$new['counter'] = (string)$item->HitCounter[0];
				$new['payment_method'] = (string)$item->PaymentMethods[0];
				$new['payment_address'] = (string)$item->PayPalEmailAddress[0];
				$new['auto_pay'] = empty($item->AutoPay[0]) ? Q::ini('custom_flag/online_ebay_listings_auto_pay/non_auto_pay/value') : Q::ini('custom_flag/online_ebay_listings_auto_pay/auto_pay/value');
				$new['dispatch_time'] = (string)$item->DispatchTimeMax[0];
				$new['get_it_fast'] = empty($item->AutoPay[0]) ? Q::ini('custom_flag/online_ebay_listings_get_it_fast/non_get_it_fast/value') : Q::ini('custom_flag/online_ebay_listings_get_it_fast/get_it_fast/value');
				$new['country'] = (string)$item->Country[0];
				$new['postal_code'] = isset($item->PostalCode[0]) ? (string)$item->PostalCode[0] : '';
				$new['location'] = isset($item->Location[0]) ? (string)$item->Location[0] : '';
				$new['return_policy'] = isset($item->ReturnPolicy[0]->ReturnsAcceptedOption[0]) ? (string)$item->ReturnPolicy[0]->ReturnsAcceptedOption[0] : '';
				$new['restocking'] = isset($item->ReturnPolicy[0]->RestockingFeeValueOption[0]) ? (string)$item->ReturnPolicy[0]->RestockingFeeValueOption[0] : '';
				$new['return_within'] = isset($item->ReturnPolicy[0]->ReturnsWithinOption[0]) ? (string)$item->ReturnPolicy[0]->ReturnsWithinOption[0] : '';
				$new['refund'] = isset($item->ReturnPolicy[0]->RefundOption[0]) ? (string)$item->ReturnPolicy[0]->RefundOption[0] : '';
				$new['paid_by'] = isset($item->ReturnPolicy[0]->ShippingCostPaidByOption[0]) ? (string)$item->ReturnPolicy[0]->ShippingCostPaidByOption[0] : '';
				$new['return_detail'] = isset($item->ReturnPolicy[0]->Description[0]) ? (string)$item->ReturnPolicy[0]->Description[0] : '';
				$new['sell_status'] = (string)$item->SellingStatus[0]->ListingStatus[0];
				$new['start_time'] = date('Y-m-d H:i:s', strtotime((string)$item->ListingDetails[0]->StartTime[0]));
				$new['end_time'] = date('Y-m-d H:i:s', strtotime((string)$item->ListingDetails[0]->EndTime[0]));
				$new['view_url'] = (string)$item->ListingDetails[0]->ViewItemURL[0];
				$new['watch_count'] = isset($item->WatchCount[0]) ? (string)$item->WatchCount[0] : '';
				if (isset($item->Variations[0]))
				{
					foreach ($item->Variations[0] as $variation)
					{
						$new['variation'] = Q::ini('custom_flag/online_ebay_listings_variation/variation/value');
						$tmp = array();
						$tmp['sku'] = (string)$variation->SKU[0];
						$tmp['quantity'] = (int)$variation->Quantity[0] - (int)$variation->SellingStatus[0]->QuantitySold[0];
						$tmp['start_price'] = (string)$variation->StartPrice[0];
						$tmp['sold_quantity'] = (int)$variation->SellingStatus[0]->QuantitySold[0];
						$tmp['buy_it_now_price'] = 0;
						$tmp['specific'] = array();
						if (isset($variation->VariationSpecifics[0]->NameValueList[0]))
						{
							foreach ($variation->VariationSpecifics[0]->NameValueList as $nvl)
							{
								$specific = array();
								$specific['name'] = (string)$nvl->Name[0];
								$specific['value'] = (string)$nvl->Value[0];
								$tmp['specific'][] = $specific;
							}
						}
						$new['item'][] = $tmp;
					}
				}
				else
				{
					$new['variation'] = Q::ini('custom_flag/online_ebay_listings_variation/non_variation/value');
					$tmp = array();
					$tmp['sku'] = (string)$item->SKU[0];
					$tmp['quantity'] = (int)$item->Quantity[0] - (int)$item->SellingStatus[0]->QuantitySold[0];
					$tmp['sold_quantity'] = (int)$item->SellingStatus[0]->QuantitySold[0];
					$tmp['start_price'] = (string)$item->StartPrice[0];
					$tmp['buy_it_now_price'] = isset($item->BuyItNowPrice[0]) ? (string)$item->BuyItNowPrice[0] : 0;
					$new['item'][] = $tmp;
				}
				$type = Q::ini('custom_flag/online_ebay_listings_picture_type/gallery/value');
				$new['picture'][$type] = array();
				if (isset($item->PictureDetails[0]->GalleryURL[0]))
				{
					$tmp = array();
					$tmp['type'] = $type;
					$tmp['specific_name'] = $tmp['specific_value'] = $tmp['picture_name'] = '';
					$tmp['picture_url'] = (string)$item->PictureDetails[0]->GalleryURL[0];
					$new['picture'][$type][] = $tmp;
				}
				$type = Q::ini('custom_flag/online_ebay_listings_picture_type/listings/value');
				$new['picture'][$type] = array();
				if (isset($item->PictureDetails[0]->PictureURL[0]))
				{
					foreach ($item->PictureDetails[0]->PictureURL as $p)
					{
						$tmp = array();
						$tmp['type'] = $type;
						$tmp['specific_name'] = $tmp['specific_value'] = $tmp['picture_name'] = '';
						$tmp['picture_url'] = (string)$p;
						$new['picture'][$type][] = $tmp;
					}
				}
				$new['shipping']['domestic'] = array();
				if (isset($item->ShippingDetails[0]->ShippingServiceOptions[0]))
				{
					$type = Q::ini('custom_flag/online_ebay_listings_shipping_type/domestic/value');
					foreach ($item->ShippingDetails[0]->ShippingServiceOptions as $s)
					{
						$shipping = array();
						$shipping['type'] = $type;
						$shipping['service'] = (string)$s->ShippingService[0];
						$shipping['cost'] = (string)$s->ShippingServiceCost[0];
						$shipping['each_cost'] = (string)$s->ShippingServiceAdditionalCost[0];
						$shipping['free'] = empty($s->FreeShipping[0]) ? Q::ini('custom_flag/online_ebay_listings_shipping_free/non_free/value') : Q::ini('custom_flag/online_ebay_listings_shipping_free/free/value');
						$shipping['shipping_location'] = '';
						$new['shipping']['domestic'][] = $shipping;
					}
				}
				$new['shipping']['internation'] = array();
				if (isset($item->ShippingDetails[0]->InternationalShippingServiceOption[0]))
				{
					$type = Q::ini('custom_flag/online_ebay_listings_shipping_type/internation/value');
					foreach ($item->ShippingDetails[0]->InternationalShippingServiceOption as $s)
					{
						$shipping = array();
						$shipping['type'] = $type;
						$shipping['service'] = (string)$s->ShippingService[0];
						$shipping['cost'] = (string)$s->ShippingServiceCost[0];
						$shipping['each_cost'] = (string)$s->ShippingServiceAdditionalCost[0];
						$shipping['free'] = Q::ini('custom_flag/online_ebay_listings_shipping/non_free/value');
						$shipping_location = '';
						if (isset($s->ShipToLocation[0]))
						{
							foreach ($s->ShipToLocation as $sll)
							{
								$shipping_location .= ',' . $sll;
							}
						}
						$shipping['shipping_location'] = trim($shipping_location, ',');
						$new['shipping']['internation'][] = $shipping;
					}
				}
				$listings[] = $new;
			}
		}
		return $listings;
	}
	
	static function ebayXMLToListingsArrayByGetItem($xml)
	{
		$new = array();
		$new['site'] = (string)$xml->Site[0];
		$new['currency_id'] = (String)$xml->Currency[0];
		$new['shop_item_id'] = (string)$xml->ItemID[0];
		$new['primary_categories'] = (string)$xml->PrimaryCategory[0]->CategoryID[0];
		$new['primary_categories_name'] = (string)$xml->PrimaryCategory[0]->CategoryName[0];
		$new['second_categories'] = isset($xml->SecondaryCategory[0]->CategoryID[0]) ? (string)$xml->SecondaryCategory[0]->CategoryID[0] : '';
		$new['second_categories_name'] = isset($xml->SecondaryCategory[0]->CategoryName[0]) ? (string)$xml->SecondaryCategory[0]->CategoryName[0] : '';
		$new['store_categories'] = isset($xml->Storefront[0]->StoreCategoryID[0]) ? (string)$xml->Storefront[0]->StoreCategoryID[0] : '';
		$new['store_categories_name'] = isset($xml->Storefront[0]->StoreCategoryName[0]) ? (string)$xml->Storefront[0]->StoreCategoryName[0] : '';
		$new['store_categories2'] = isset($xml->Storefront[0]->StoreCategory2ID[0]) ? (string)$xml->Storefront[0]->StoreCategory2ID[0] : '';
		$new['store_categories2_name'] = isset($xml->Storefront[0]->StoreCategory2Name[0]) ? (string)$xml->Storefront[0]->StoreCategory2Name[0] : '';
		$new['title'] = (string)$xml->Title[0];
		$new['condition_id'] = isset($xml->ConditionID[0]) ? (string)$xml->ConditionID[0] : '';
		$new['condition_name'] = isset($xml->ConditionDisplayName[0]) ? (string)$xml->ConditionDisplayName[0] : '';
		$new['condition_description'] = isset($xml->ConditionDescription[0]) ? (string)$xml->ConditionDescription[0] : '';
		$new['description'] = isset($xml->Description[0]) ? (string)$xml->Description[0] : '';
		$new['listing_type'] = (string)$xml->ListingType[0];
		$new['listing_duration'] = (string)$xml->ListingDuration[0];
		$new['counter'] = (string)$xml->HitCounter[0];
		$new['payment_method'] = (string)$xml->PaymentMethods[0];
		$new['payment_address'] = (string)$xml->PayPalEmailAddress[0];
		$new['auto_pay'] = empty($xml->AutoPay[0]) ? Q::ini('custom_flag/online_ebay_listings_auto_pay/non_auto_pay/value') : Q::ini('custom_flag/online_ebay_listings_auto_pay/auto_pay/value');
		$new['dispatch_time'] = (string)$xml->DispatchTimeMax[0];
		$new['get_it_fast'] = empty($xml->AutoPay[0]) ? Q::ini('custom_flag/online_ebay_listings_get_it_fast/non_get_it_fast/value') : Q::ini('custom_flag/online_ebay_listings_get_it_fast/get_it_fast/value');
		$new['country'] = (string)$xml->Country[0];
		$new['postal_code'] = isset($xml->PostalCode[0]) ? (string)$xml->PostalCode[0] : '';
		$new['location'] = isset($xml->Location[0]) ? (string)$xml->Location[0] : '';
		$new['return_policy'] = isset($xml->ReturnPolicy[0]->ReturnsAcceptedOption[0]) ? (string)$xml->ReturnPolicy[0]->ReturnsAcceptedOption[0] : '';
		$new['restocking'] = isset($xml->ReturnPolicy[0]->RestockingFeeValueOption[0]) ? (string)$xml->ReturnPolicy[0]->RestockingFeeValueOption[0] : '';
		$new['return_within'] = isset($xml->ReturnPolicy[0]->ReturnsWithinOption[0]) ? (string)$xml->ReturnPolicy[0]->ReturnsWithinOption[0] : '';
		$new['refund'] = isset($xml->ReturnPolicy[0]->RefundOption[0]) ? (string)$xml->ReturnPolicy[0]->RefundOption[0] : '';
		$new['paid_by'] = isset($xml->ReturnPolicy[0]->ShippingCostPaidByOption[0]) ? (string)$xml->ReturnPolicy[0]->ShippingCostPaidByOption[0] : '';
		$new['return_detail'] = isset($xml->ReturnPolicy[0]->Description[0]) ? (string)$xml->ReturnPolicy[0]->Description[0] : '';
		$new['sell_status'] = (string)$xml->SellingStatus[0]->ListingStatus[0];
		$new['start_time'] = date('Y-m-d H:i:s', strtotime((string)$xml->ListingDetails[0]->StartTime[0]));
		$new['end_time'] = date('Y-m-d H:i:s', strtotime((string)$xml->ListingDetails[0]->EndTime[0]));
		$new['view_url'] = (string)$xml->ListingDetails[0]->ViewItemURL[0];
		$new['watch_count'] = isset($xml->WatchCount[0]) ? (string)$xml->WatchCount[0] : '';
		if (isset($xml->Variations[0]->Variation[0]))
		{
			foreach ($xml->Variations[0]->Variation as $variation)
			{
				$new['variation'] = Q::ini('custom_flag/online_ebay_listings_variation/variation/value');
				$tmp = array();
				$tmp['sku'] = (string)$variation->SKU[0];
				$tmp['quantity'] = (int)$variation->Quantity[0] - (int)$variation->SellingStatus[0]->QuantitySold[0];
				$tmp['start_price'] = (string)$variation->StartPrice[0];
				$tmp['sold_quantity'] = (int)$variation->SellingStatus[0]->QuantitySold[0];
				$tmp['buy_it_now_price'] = 0;
				$tmp['specific'] = array();
				if (isset($variation->VariationSpecifics[0]->NameValueList[0]))
				{
					foreach ($variation->VariationSpecifics[0]->NameValueList as $nvl)
					{
						$specific = array();
						$specific['name'] = (string)$nvl->Name[0];
						$specific['value'] = (string)$nvl->Value[0];
						$tmp['specific'][] = $specific;
					}
				}
				$new['item'][] = $tmp;
			}
		}
		else
		{
			$new['variation'] = Q::ini('custom_flag/online_ebay_listings_variation/non_variation/value');
			$tmp = array();
			$tmp['sku'] = (string)$xml->SKU[0];
			$tmp['quantity'] = (int)$xml->Quantity[0] - (int)$xml->SellingStatus[0]->QuantitySold[0];
			$tmp['sold_quantity'] = (int)$xml->SellingStatus[0]->QuantitySold[0];
			$tmp['start_price'] = (string)$xml->StartPrice[0];
			$tmp['buy_it_now_price'] = isset($xml->BuyItNowPrice[0]) ? (string)$xml->BuyItNowPrice[0] : 0;
			$new['item'][] = $tmp;
		}
		$type = Q::ini('custom_flag/online_ebay_listings_picture_type/gallery/value');
		$new['picture'][$type] = array();
		if (isset($xml->PictureDetails[0]->GalleryURL[0]))
		{
			$tmp = array();
			$tmp['type'] = $type;
			$tmp['specific_name'] = $tmp['specific_value'] = $tmp['picture_name'] = '';
			$tmp['picture_url'] = (string)$xml->PictureDetails[0]->GalleryURL[0];
			$new['picture'][$type][] = $tmp;
		}
		$type = Q::ini('custom_flag/online_ebay_listings_picture_type/listings/value');
		$new['picture'][$type] = array();
		if (isset($xml->PictureDetails[0]->PictureURL[0]))
		{
			foreach ($xml->PictureDetails[0]->PictureURL as $p)
			{
				$tmp = array();
				$tmp['type'] = $type;
				$tmp['specific_name'] = $tmp['specific_value'] = $tmp['picture_name'] = '';
				$tmp['picture_url'] = (string)$p;
				$new['picture'][$type][] = $tmp;
			}
		}
		$type = Q::ini('custom_flag/online_ebay_listings_picture_type/variation/value');
		$new['picture'][$type] = array();
		if (isset($xml->Variations[0]->Pictures[0]))
		{
			$name = (string)$xml->Variations[0]->Pictures[0]->VariationSpecificName[0];
			foreach ($xml->Variations[0]->Pictures[0]->VariationSpecificPictureSet as $p)
			{
				$value = (string)$p->VariationSpecificValue;
				foreach ($p->PictureURL as $pu)
				{
					$tmp = array();
					$tmp['type'] = $type;
					$tmp['specific_name'] = $name;
					$tmp['specific_value'] = $value;
					$tmp['picture_name'] = '';
					$tmp['picture_url'] = (string)$pu;
					$new['picture'][$type][] = $tmp;
				}
			}
		}
		$new['shipping']['domestic'] = array();
		if (isset($xml->ShippingDetails[0]->ShippingServiceOptions[0]))
		{
			$type = Q::ini('custom_flag/online_ebay_listings_shipping_type/domestic/value');
			foreach ($xml->ShippingDetails[0]->ShippingServiceOptions as $s)
			{
				$shipping = array();
				$shipping['type'] = $type;
				$shipping['service'] = (string)$s->ShippingService[0];
				$shipping['cost'] = (string)$s->ShippingServiceCost[0];
				$shipping['each_cost'] = (string)$s->ShippingServiceAdditionalCost[0];
				$shipping['free'] = empty($s->FreeShipping[0]) ? Q::ini('custom_flag/online_ebay_listings_shipping_free/non_free/value') : Q::ini('custom_flag/online_ebay_listings_shipping_free/free/value');
				$shipping['shipping_location'] = '';
				$new['shipping']['domestic'][] = $shipping;
			}
		}
		$new['shipping']['internation'] = array();
		if (isset($xml->ShippingDetails[0]->InternationalShippingServiceOption[0]))
		{
			$type = Q::ini('custom_flag/online_ebay_listings_shipping_type/internation/value');
			foreach ($xml->ShippingDetails[0]->InternationalShippingServiceOption as $s)
			{
				$shipping = array();
				$shipping['type'] = $type;
				$shipping['service'] = (string)$s->ShippingService[0];
				$shipping['cost'] = (string)$s->ShippingServiceCost[0];
				$shipping['each_cost'] = (string)$s->ShippingServiceAdditionalCost[0];
				$shipping['free'] = Q::ini('custom_flag/online_ebay_listings_shipping/non_free/value');
				$shipping_location = '';
				if (isset($s->ShipToLocation[0]))
				{
					foreach ($s->ShipToLocation as $sll)
					{
						$shipping_location .= ',' . $sll;
					}
				}
				$shipping['shipping_location'] = trim($shipping_location, ',');
				$new['shipping']['internation'][] = $shipping;
			}
		}
		$new['specific'] = array();
		if (isset($xml->ItemSpecifics[0]->NameValueList[0]))
		{
			foreach ($xml->ItemSpecifics[0]->NameValueList as $nvl)
			{
				$specific = array();
				$specific['name'] = (string)$nvl->Name[0];
				$specific['value'] = (string)$nvl->Value[0];
				$new['specific'][] = $specific;
			}
		}
		return $new;
	}
	
	static function ebayXmlToVerifyArray($xml)
	{
		$verify = array();
		$verify['ack'] = (string)$xml->Ack[0];
		$errors = array();
		if (isset($xml->Errors[0]))
		{
			foreach ($xml->Errors as $e)
			{
				$errors[] = (string)$e->LongMessage[0];
			}
		}
		$verify['errors'] = $errors;
		$total_fees = 0;
		$fees = array();
		if (isset($xml->Fees[0]->Fee[0]))
		{
			foreach ($xml->Fees[0]->Fee as $f)
			{
				$value = (float)$f->Fee[0];
				if ($value)
				{
					$name = (string)$f->Name[0];
					if ($name == 'ListingFee')
					{
						$total_fees = sprintf('%.4f', $value);
					}
					else
					{
						$fees[] = array(
							'name' => (string)$f->Name[0],
							'value' => sprintf('%.4f', $value),
						);
					}
				}
			}
		}
		$verify['fees'] = $fees;
		$verify['total_fees'] = sprintf('%.4f', $total_fees);
		return $verify;
	}
}